package org.example.blog.controller;

import com.sun.org.apache.bcel.internal.generic.IUSHR;
import org.example.blog.model.BlogInfo;
import org.example.blog.service.BlogService;
import org.example.blog.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    @RequestMapping("/getlist")//获取博客列表
    public List<BlogInfo> getBlogList(){
       return blogService.getBlogList();
    }
    //获取博客详情
    @RequestMapping("/getdetail")
    public BlogInfo getBlogDetail(Integer blogId, HttpServletRequest request){
        BlogInfo blogInfo = blogService.getBlogDeatil(blogId);
        //判断作者是否为登录用户
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if (userId != null && userId == blogInfo.getUserId()){
            blogInfo.setLoginUser(true);
        }
         return blogInfo;
    }
    //发布博客
    @RequestMapping("/add")
    public boolean publistBlog(String title, String content, HttpServletRequest request){

        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);
        if(userId == null || userId<0){
            return false;
        }

        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setUserId(userId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.insertBlog(blogInfo);
        return true;
    }
   @RequestMapping("/update")
    public boolean updateBlog(BlogInfo blogInfo){
        blogService.updateBlog(blogInfo);
        return true;
    }
    @RequestMapping("/delete")
    public boolean deleteBlog(Integer id){
        blogService.deleteBlog(id);
        return true;
    }
}
